package com.leizi.igym.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leizi.igym.BaseContext.UserThreadLocal;
import com.leizi.igym.domain.User;
import com.leizi.igym.dto.*;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.resp.Result;
import com.leizi.igym.service.EmployeeService;
import com.leizi.igym.service.UserService;
import com.leizi.igym.utils.ThrowUtils;
import com.leizi.igym.vo.UserLoginVO;
import com.leizi.igym.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-04  16:50
 * @Description:
 */
@RestController("userUserController")
@RequestMapping("/user/user")
@Tag(name = "用户端-用户相关接口")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private EmployeeService employeeService;

    @Operation(summary = "用户端：用户登录")
    @PostMapping("login")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO dto) {
        log.info("用户端正在执行登录操作，{}", dto);
        // 校验传回的dto是否合法
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        // 校验账号和密码
        String username = dto.getUsername();
        String password = dto.getPassword();
        ThrowUtils.throwIf(StringUtils.isAnyBlank(username, password), ReturnCodeEnum.PARAMS_ERROR);
        return Result.ok(userService.userLoginInUser(username, password));
    }

    @Operation(summary = "用户端：用户注销")
    @PostMapping("/logout")
    public Result userLogout() {
        // 移除登录态
        UserThreadLocal.remove();
        return Result.ok("注销成功");
    }

    @Operation(summary = "用户端：用户注册")
    @PostMapping("/register")
    public Result<Long> userRegister(@RequestBody UserRegisterDTO dto) {
        log.info("用户端正在执行注册操作，{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        String username = dto.getUsername();
        String password = dto.getPassword();
        String checkPassword = dto.getCheckPassword();
        ThrowUtils.throwIf(StringUtils.isAnyBlank(username,
                checkPassword,
                password), ReturnCodeEnum.PARAMS_ERROR);
        Long id = userService.registerUser(username, password, checkPassword);
        return Result.ok(id);
    }

    @Operation(summary = "用户端：用户修改个人信息")
    @PutMapping("/edit")
    public Result editUserInUser(@RequestBody UserEditDTO dto) {
        log.info("用户正在修改个人信息，修改参数为：{}", dto);

        // 校验修改参数
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.NOT_LOGIN_ERROR);

        // 构造用户对象
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        return Result.ok(userService.editByIdInUser(user));
    }

    @Operation(summary = "用户端：用户修改个人密码")
    @PutMapping("password")
    public Result updatePasswordInUser(@RequestBody ModifyPasswordDTO dto) {
        log.info("用户端正在修改个人密码，修改参数为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);

        // 简单校验密码是否合法
        String originPassword = dto.getOldPassword();
        String newPassword = dto.getNewPassword();
        String checkPassword = dto.getCheckPassword();
        ThrowUtils.throwIf(ObjectUtils.allNull(originPassword,
                        newPassword,
                        checkPassword),
                ReturnCodeEnum.PARAMS_ERROR);
        boolean result = userService.updatePasswordInUser(originPassword, newPassword, checkPassword);
        return Result.ok(result);
    }

    @Operation(summary = "用户端：成为员工")
    @PutMapping("beEmp")
    public Result<Long> toBeEmp(@RequestBody EmployeeAddDTO dto) {
        log.info("用户端正在执行成为员工操作，参数为：{}", dto);
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        long result = employeeService.addEmp(dto);
        return result == -1 ? Result.fail(ReturnCodeEnum.SYSTEM_ERROR, "插入员工信息失败！") :
                Result.ok(result);
    }

    @Operation(summary = "用户端：微信登录")
    @GetMapping("/wx")
    public Result wxLogin(@RequestParam("code") String code) throws IOException {
        log.info("用户端正在执行微信操作");
        if (StringUtils.isBlank(code)) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR, "登录异常！");
        }
        UserLoginVO userLoginVO = userService.wxLogin(code);
        return Result.ok(userLoginVO);
    }

    @Operation(summary = "用户端：根据id获取用户")
    @GetMapping("/{id}")
    public Result wxLogin(@PathVariable("id") Long id){
        if (Objects.isNull(id) || id<0) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }
        UserVO userById = userService.getUserById(id);
        return Result.ok(userById);
    }

    @Operation(summary = "用户端：检验用户名是否重复")
    @GetMapping("/validateUsername")
    public Result validateUsername(@RequestParam(value = "username",required = false) String username) {
        log.info("用户端正在执行检验用户名是否重复操作");
        if (StringUtils.isBlank(username)) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR, "登录异常！");
        }
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        long count = userService.count(qw);
        if (count >= 1) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR,"用户名重复");
        }
        return Result.ok(true);
    }
}
